from lib.net import wifi
from lib.api import iot
from lib.sensors.soil import LM393
from lib.config.index import sensor_config
from utils import common
import json
from lib.sensors.oled import ops
from machine import SoftI2C

wifi.do_connect_wifi()


config = sensor_config.get_sensor("LM393")
print(config)
A0 = config["A0"]
D0 = config["D0"]


config = sensor_config.get_sensor("ssd1306")
# print(config)
scl = config["scl"]
sda = config["sda"]

f = open("/www/fonts_12.json", "r")
data = f.read()
fonts = json.loads(data)
f.close()
ops.set_font(fonts, 12)

i2c = SoftI2C(scl, sda)

ops.init_oled(scl, sda)
ops.reset_line()
ops.show_text("开始测量数据...")


soil = LM393.Soil(A0, D0)


def demo():
    import time

    while True:
        v = soil.read_analog()
        hu = round(100 - v / 40.96, 2)
        time.sleep(3)
        data = {"humidity": hu, "value": v}
        print(data)
        iot.upload_data(data, "Tiot_xtbrkh2t")
        ops.clear()
        ops.auto_text(f"湿度: {hu}%", 0, 0, 12)


if __name__ == "__main__":
    demo()
